package com.example.leero.graduation.Util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImageUtil {
  private static final String TAG = "ImageUtil";

  /**
   * 压缩图片
   * @param pathName
   * @param targetDir
   * @param quality
   * @return
   */
  public static String compressImage(String pathName, String targetDir, int quality) {
    Bitmap bm = getSampledBitmap(pathName, 300, 300);
    File file = new File(pathName);
    Log.e(TAG, "origin size: " + file.length());
    String fileName = file.getName();
    File outputFile = new File(targetDir, fileName);
    try {
        if (!outputFile.exists()) {
            outputFile.getParentFile().mkdirs();
        } else {
            outputFile.delete();
        }

        FileOutputStream out = new FileOutputStream(outputFile);
        bm.compress(Bitmap.CompressFormat.JPEG, quality, out);

    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.e(TAG, "compressed size: " + outputFile.length());
    file = null;
    return outputFile.getPath();
  }

  public static Bitmap getSampledBitmap(String pathName, int reqWidth, int reqHeight) {
      // First decode with inJustDecodeBounds=true to check dimensions
      final BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeFile(pathName, options);

      // Calculate inSampleSize
      options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

      options.inJustDecodeBounds = false;
      return BitmapFactory.decodeFile(pathName, options);
  }

  public static int calculateInSampleSize(
          BitmapFactory.Options options, int reqWidth, int reqHeight) {
      // Raw height and width of image
      final int height = options.outHeight;
      final int width = options.outWidth;
      int inSampleSize = 1;

      if (height > reqHeight || width > reqWidth) {

          final int halfHeight = height / 2;
          final int halfWidth = width / 2;

          // Calculate the largest inSampleSize value that is a power of 2 and keeps both
          // height and width larger than the requested height and width.
          while ((halfHeight / inSampleSize) >= reqHeight
                  && (halfWidth / inSampleSize) >= reqWidth) {
              inSampleSize *= 2;
          }
      }

      return inSampleSize;
  }

}
